// pages/cvInterviewJob/cvInterviewJob.js
const db = wx.cloud.database({
    env: 'work1-0g1b3grp436e9236'
})
const util = require('../../utils/util')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 还没有人投递
        isNull: false,
        cvList: [],
        loading: true,
        curPage: 0,
        // 修改简历状态弹出框
        showUpdateAction: false,
        updateActions: [{
                name: '已投递',
                value: 0,
                color: '#00a896'
            }, {
                name: '待笔试',
                value: 1,
                color: '#00a896'
            },
            {
                name: '笔试通过',
                value: 2,
                color: '#00a896'
            }, {
                name: '待面试',
                value: 3,
                color: '#00a896'
            },
            {
                name: '录用失败',
                value: 4,
                color: '#00a896'
            }, {
                name: '录用成功',
                value: 5,
                color: '#00a896'
            }
        ],
    },

    // 发送私信
    toPrivateChat(e) {
        const userInfo = wx.getStorageSync('userInfo')
        if (!userInfo) {
          util.myToastNone('请先登录～')
            return
        }
        const toOpenId = e.currentTarget.dataset.id
        // console.log(toOpenId)
        if (toOpenId === userInfo.userOpenId) {
            util.myToastError('不能发给自己～')
            return
        }
        wx.navigateTo({
          url: '/pages/privateChat/privateChat?to=' + toOpenId,
        })
    },

    // 查看简历
    toCvDetail(e) {
        const cvId = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/cv-preview/cv-preview?_id=' + cvId
        })
    },

    // 修改简历状态
    updateCvStatus(e) {
        this.setData({
            showUpdateAction: true
        })
        const postId = e.currentTarget.dataset.id
        this.setData({
            toUpdatePostId: postId
        })
    },

    onCloseUpdateActionSheet() {
        this.setData({
            showUpdateAction: false
        })
    },

    async onSelectUpdateActionSheet(e) {
        const target = e.detail.value
        let isRemainNumEqZero = false
        let isRepeatModification = false
        switch (target) {
            case 6:
                this.setData({
                    showUpdateAction: false
                })
                break;
            default:
                for (let i = 0; i < this.data.cvList.length; i++) {
                    const element = this.data.cvList[i];
                    if (element._id === this.data.toUpdatePostId) {
                        // 不能被重复修改
                        if (target <= element.status) {
                            isRepeatModification = true
                            break
                        }
                        // 对录用成功进行判断
                        if (target === 5) {
                            // job中的remainNum--
                            const _ = db.command
                            const res = await db.collection('work_job').doc(element.jobId).get()
                            if (res.data.remainNum > 0) {
                                db.collection('work_job').doc(element.jobId).update({
                                    data: {
                                        remainNum: _.inc(-1)
                                    },
                                }).then(res => {
                                    element.status = target
                                    this.setData({
                                        cvList: this.data.cvList
                                    })
                                    db.collection('work_user').doc(element.userId).get().then(res=>{
                                        console.log(res)
                                        // 给该用户通知
                                        util.sendMessage('【录用成功通知】' +  element.realName + '：你已通过本公司的全部应聘考核，恭喜你被成功录用！', res.data.openid, res.data.nickName, res.data.avatar)
                                    })
                                })
                            } else {
                                isRemainNumEqZero = true
                            }
                        } else {
                            element.status = target
                            this.setData({
                                cvList: this.data.cvList
                            })
                        }
                        break
                    }
                }
                if (isRepeatModification) {
                    util.myToastError('不能重复~')
                    this.setData({
                        showUpdateAction: false
                    })
                    break
                }
                if (isRemainNumEqZero) {
                    util.myToastError('该职位人数已满')
                    this.setData({
                        showUpdateAction: false
                    })
                    break
                }
                // 将数据库数据修改
                db.collection('work_post').doc(this.data.toUpdatePostId).update({
                    data: {
                        status: target
                    }
                }).then(res => {
                    util.myToastSuccess('修改成功')
                }).catch(res => {
                    console.log('修改简历状态失败~', res)
                })
                // 记录修改过程
                db.collection('work_cv_status_record').add({
                    data: {
                        postId: this.data.toUpdatePostId,
                        status: target,
                        updateTime: new Date()
                    }
                }).then(res => {
                    util.myToastSuccess('修改成功')
                }).catch(res => {
                    console.log('修改简历状态失败~', res)
                })
                this.setData({
                    showUpdateAction: false
                })
                break
        }
    },

    async getCvList(limit = 10) {
        const res = await db.collection('work_post').skip(this.data.curPage * limit).limit(limit).where({
            jobId: this.data.jobId
        }).get()
        this.setData({
            cvList: this.data.cvList.concat(res.data),
            loading: false
        })
        // console.log(this.data.cvList)
        if (this.data.cvList.length === 0) {
            this.setData({
                isNull: true
            })
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const jobId = options.id
        this.setData({
            jobId: jobId
        })
        this.getCvList()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    async onPullDownRefresh() {
        wx.showNavigationBarLoading()
        this.setData({
            cvList: [],
            curPage: 0,
            loading: true
        })
        await this.getCvList()
        wx.hideNavigationBarLoading()
        // 数据成功后，停止下拉刷新
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        wx.showLoading({
            title: '加载中..',
        })
        this.setData({
            curPage: this.data.curPage + 1
        })
        this.getCvList().then(() => {
            // 数据成功后，停止下拉刷新
            wx.stopPullDownRefresh()
            wx.hideLoading()
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})